var config = require("../../config");
var Download = require("../models/download");
var laypage=require("laypage");
var async = require('async');

//课程列表
exports.list = function (req, res) {
	var pageSize = 10; //每页显示条数
	var page = req.params.num - 1 || 0;
	Download.find().count().exec(function (err, sum) {
		Download.find().limit(pageSize).skip(pageSize * page).sort({_id: -1}).exec(function (err, _download) {
            res.render('admin/downloadList', {
                title: '课程列表',
                laypage: laypage({
                    curr: req.params.num || 1,
                    url: req.url, //必传参数，获取当前页的url
                    groups: 5,
                    pages: Math.ceil(sum/pageSize), //分页总数你需要通过sql查询得到
                    prev: '‹',
                    next: '›'
                }),
                download:_download,
                pagesize: sum
            })
		});
	});
}

//添加资料
exports.add = function (req, res) {
    res.render('admin/downloadAdd', {
        title: '添加资料'
    })
}

exports.update = function (req, res) {
	var _cases = req.params;
    Download.findOne({
        "_id": _cases.id
    }, function (err, _download) {
        var subStr=new RegExp('/attachment/')
        _download.dataLink = _download.dataLink.replace(subStr,'')
        res.render('admin/downloadEdit', {
            title: '编辑资料',
            download: _download
        })
	});
}

//案例提交与更新
exports.save = function (req, res) {
	var _downLoadBody = req.body;
	var _body = {
			name: _downLoadBody.name,
			dataLink:_downLoadBody.dataLink
		}

	if (_downLoadBody._id) {
		var id = _downLoadBody._id;
		Download.update({
			_id: id
		}, _body, function (err, category) {
			res.redirect("/admin/downloadList");
		});
	} else {
		Download.create(_body, function (err, category) {
			res.redirect("/admin/downloadList");
		});
	}

}

//提交与更新
exports.delete = function (req, res) {
	var id = req.params.id;
	Download.remove({
		_id: id
	}, function (err, cases) {
		res.redirect("/admin/downloadList");
	})
}
